let ws;
let username, roomId;
let lastSeq = 0; // track last received seq for this room
let heartbeatTimer;
let reconnectDelay = 1000;
let onlineUsers = new Set(); // 在线用户列表
let activeChat = 'group'; // 当前激活的聊天：'group' 或用户名
let privateChatTabs = new Map(); // 私聊标签页映射：用户名 -> 标签信息
let unreadCounts = new Map(); // 未读消息计数
let readMessages = new Map(); // 已读消息记录：chatId -> Set<messageId>

// ✅ 消息去重：存储已接收消息的 ID（roomId-seq）
const receivedMessageIds = new Set();
const MAX_MESSAGE_CACHE = 1000;

// ✅ 页面加载时检查登录状态
window.addEventListener('DOMContentLoaded', async function() {
    try {
        const response = await fetch('/auth/current');
        const data = await response.json();
        
        console.log('Chat页面检查登录状态:', data); // 调试日志
        
        if (data.code === 200 && data.data && data.data.username) {
            // 已登录，自动进入聊天室
            username = data.data.username;
            roomId = data.data.roomId || 'default';
            
            document.getElementById('login').style.display = 'none';
            document.getElementById('chat').style.display = 'flex';
            
            // 更新侧边栏用户信息
            document.getElementById('curRoom').textContent = roomId;
            document.getElementById('chatRoomName').textContent = roomId;
            document.getElementById('sidebarUsername').textContent = username;
            document.getElementById('sidebarAvatar').textContent = getAvatar(username);
            
            // 初始化在线用户列表
            onlineUsers.clear();
            onlineUsers.add(username);
            updateOnlineUsersList();

            // 初始化聊天输入和标签页
            initChatInputEvents();
            initGroupChatTab();

            // 加载好友列表
            loadFriendsList();

            // 从 localStorage 恢复已读消息记录和未读计数
            loadReadMessagesFromStorage();
            loadUnreadCountsFromStorage();

            connect();
        } else {
            // 未登录，重定向到登录页面
            window.location.href = 'login.html';
        }
    } catch (error) {
        // 检查失败，重定向到登录页面
        console.error('检查登录状态失败:', error);
        window.location.href = 'login.html';
    }
});

document.getElementById('btnLogin').addEventListener('click', async () => {
    username = document.getElementById('username').value.trim();
    roomId = document.getElementById('roomId').value.trim() || 'default';
    if (!username) return alert('请输入用户名');

    // login via HTTP (session stored in Redis by Spring Session)
    await fetch('/auth/login', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `username=${encodeURIComponent(username)}&roomId=${encodeURIComponent(roomId)}`
    });

    document.getElementById('login').style.display = 'none';
    document.getElementById('chat').style.display = 'flex';
    
    // 更新侧边栏用户信息
    document.getElementById('curRoom').textContent = roomId;
    document.getElementById('chatRoomName').textContent = roomId;
    document.getElementById('sidebarUsername').textContent = username;
    document.getElementById('sidebarAvatar').textContent = getAvatar(username);
    
    // 初始化在线用户列表
    onlineUsers.clear();
    onlineUsers.add(username);
    updateOnlineUsersList();

    // 初始化聊天输入和标签页
    initChatInputEvents();
    initGroupChatTab();

    connect();
});

// 支持回车登录
document.getElementById('username').addEventListener('keypress', (e) => {
    if (e.key === 'Enter') document.getElementById('btnLogin').click();
});
document.getElementById('roomId').addEventListener('keypress', (e) => {
    if (e.key === 'Enter') document.getElementById('btnLogin').click();
});

function connect() {
    ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws/chat');

    ws.onopen = () => {
        console.log('ws open');
        updateConnectionStatus(true);
        reconnectDelay = 1000;
        startHeartbeat();

        // ✅ 拉取在线用户列表
        fetch(`/auth/online-users?roomId=${encodeURIComponent(roomId)}`)
            .then(r => r.json())
            .then(response => {
                if (response && response.code === 200 && response.data) {
                    console.log('Loaded online users:', response.data);
                    // 更新在线用户列表
                    onlineUsers.clear();
                    response.data.forEach(user => onlineUsers.add(user));
                    updateOnlineUsersList();
                }
            })
            .catch(err => console.error('Failed to load online users:', err));

        // 拉取最近消息（redis）显示
        fetch(`/history/recent?roomId=${encodeURIComponent(roomId)}&limit=100`)
            .then(r => r.json())
            .then(response => {
                // ✅ 适配新的响应格式
                const arr = response.code === 200 ? response.data : response;
                if (arr && arr.length) {
                    console.log('Loaded history messages:', arr.length);
                    // arr 是 redis 中的 JSON 字符串（最新在前），我们逆序显示
                    arr.reverse().forEach(s => {
                        // s 已经是 JSON 字符串，直接传递
                        handleIncoming(s);
                    });
                    // set lastSeq 为最后一条的 seq（如果有）
                    try {
                        const last = arr[arr.length - 1];
                        const lastMsg = typeof last === 'string' ? JSON.parse(last) : last;
                        if (lastMsg && lastMsg.seq) lastSeq = lastMsg.seq;
                    } catch (e) {
                        console.error('Failed to parse last message seq:', e);
                    }
                }
            })
            .catch(err => console.error('Failed to load history:', err));
    };

    ws.onmessage = (evt) => {
        handleIncoming(evt.data);
    };

    ws.onclose = () => {
        console.log('ws closed, try reconnect');
        updateConnectionStatus(false);
        stopHeartbeat();
        setTimeout(connect, reconnectDelay);
        reconnectDelay = Math.min(30000, reconnectDelay * 2);

        // 重连后向服务端请求自 lastSeq 后的消息
        setTimeout(() => {
            fetch(`/history/since?roomId=${encodeURIComponent(roomId)}&sinceSeq=${lastSeq}`)
                .then(r => r.json())
                .then(response => {
                    // ✅ 适配新的响应格式
                    const arr = response.code === 200 ? response.data : response;
                    if (arr && arr.length) {
                        arr.forEach(m => {
                            // m.content 是我们存入 DB 的 JSON 字符串
                            handleIncoming(m.content);
                        });
                    }
                });
        }, 1500);
    };

    ws.onerror = (e) => console.error(e);
}

function startHeartbeat() {
    heartbeatTimer = setInterval(() => {
        if (ws && ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify({type: 'ping', ts: Date.now()}));
        }
    }, 20000);
}

function stopHeartbeat() {
    clearInterval(heartbeatTimer);
}

function sendMessage(inputElement, toUser = null) {
    const text = inputElement.value.trim();
    
    if (!text) {
        console.warn('Cannot send empty message');
        return;
    }
    
    const payload = {
        type: 'chat',
        roomId: roomId,
        toUser: toUser,
        content: text
    };
    
    console.log('Sending message:', payload);
    ws.send(JSON.stringify(payload));
    inputElement.value = '';
}

// 初始化群聊输入事件
function initChatInputEvents() {
    // 群聊输入
    const groupArea = document.querySelector('[data-chat-id="group"]');
    if (!groupArea) {
        console.error('Group chat area not found!');
        return;
    }
    
    const groupInput = groupArea.querySelector('.message-input');
    const groupSendBtn = groupArea.querySelector('.send-btn');
    
    if (!groupInput || !groupSendBtn) {
        console.error('Group chat input elements not found!');
        return;
    }
    
    groupSendBtn.addEventListener('click', () => sendMessage(groupInput, null));
    groupInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') sendMessage(groupInput, null);
    });
    
    console.log('Chat input events initialized');
}

// 初始化群聊标签点击事件
function initGroupChatTab() {
    const groupTab = document.querySelector('[data-chat-id="group"]');
    if (groupTab) {
        groupTab.addEventListener('click', () => switchToChat('group'));
        console.log('Group chat tab initialized');
    } else {
        console.error('Group chat tab not found!');
    }
}

function handleIncoming(data) {
    // data could be JSON string or object; ensure we have object with seq, fromName, message
    let obj;
    try {
        obj = typeof data === 'string' ? JSON.parse(data) : data;
        console.log('Received message:', obj);
    } catch (e) {
        console.error('Failed to parse message:', data, e);
        return;
    }
    
    // 验证消息对象的基本字段
    if (!obj || typeof obj !== 'object') {
        console.error('Invalid message object:', obj);
        return;
    }
    
    // update lastSeq if present
    if (obj.seq) lastSeq = Math.max(lastSeq, obj.seq);
    
    // 获取消息内容
    let msgContent = '';
    if (obj.message !== undefined && obj.message !== null) {
        msgContent = typeof obj.message === 'string' ? obj.message : JSON.stringify(obj.message);
        msgContent = msgContent.trim();
    }
    
    // 如果是空消息但不是系统消息，跳过
    if (!msgContent && !obj.system) {
        console.warn('Empty message content, skipping:', obj);
        return;
    }
    
    // 系统消息 - 只显示在群聊
    if (obj.system) {
        const div = createSystemMessage(msgContent);
        const groupMessages = document.getElementById('messages-group');
        removeWelcomeMessage(groupMessages);
        groupMessages.appendChild(div);
        scrollToBottomOf(groupMessages);
        
        // 处理用户加入/离开
        if (msgContent.includes(' joined')) {
            const userName = msgContent.replace(' joined', '').trim();
            onlineUsers.add(userName);
            updateOnlineUsersList();
            addSystemNotification(`${userName} 加入了房间`);
        } else if (msgContent.includes(' left')) {
            const userName = msgContent.replace(' left', '').trim();
            onlineUsers.delete(userName);
            updateOnlineUsersList();
            addSystemNotification(`${userName} 离开了房间`);
        }
    } else {
        // 普通消息 - 分发到群聊或私聊
        const isOwn = obj.fromName === username;
        
        // 添加到在线用户列表
        if (obj.fromName) {
            onlineUsers.add(obj.fromName);
            updateOnlineUsersList();
        }
        
        // 判断是群聊还是私聊
        if (obj.toUser) {
            // 私聊消息
            const chatPartner = isOwn ? obj.toUser : obj.fromName;
            
            // 确保私聊标签存在
            if (!privateChatTabs.has(chatPartner)) {
                createPrivateChatTab(chatPartner);
            }
            
            // 添加消息到私聊区域
            const privateMessages = document.getElementById(`messages-${chatPartner}`);
            const div = createChatMessage(obj, msgContent, isOwn);
            removeWelcomeMessage(privateMessages);
            privateMessages.appendChild(div);
            
            // 如果不是当前激活的聊天，增加未读计数
            if (activeChat !== chatPartner) {
                increaseUnreadCount(chatPartner);
            } else {
                scrollToBottomOf(privateMessages);
            }
        } else {
            // 群聊消息
            const groupMessages = document.getElementById('messages-group');
            const div = createChatMessage(obj, msgContent, isOwn);
            removeWelcomeMessage(groupMessages);
            groupMessages.appendChild(div);
            
            // 如果不是当前激活群聊，增加未读计数
            if (activeChat !== 'group') {
                increaseUnreadCount('group');
            } else {
                scrollToBottomOf(groupMessages);
            }
        }
    }
}

// ========== 标签页管理 ==========

function createPrivateChatTab(userName) {
    if (privateChatTabs.has(userName)) return;
    
    const tabsContainer = document.getElementById('chat-tabs');
    const contentContainer = document.getElementById('chat-content');
    
    // 创建标签
    const tab = document.createElement('div');
    tab.className = 'chat-tab';
    tab.dataset.chatType = 'private';
    tab.dataset.chatId = userName;
    tab.innerHTML = `
        <span class="tab-icon">👤</span>
        <span class="tab-name">${escapeHtml(userName)}</span>
        <span class="unread-badge" style="display:none;">0</span>
        <span class="tab-close">×</span>
    `;
    
    // 标签点击事件
    tab.addEventListener('click', (e) => {
        if (e.target.classList.contains('tab-close')) {
            closePrivateChatTab(userName);
        } else {
            switchToChat(userName);
        }
    });
    
    tabsContainer.appendChild(tab);
    
    // 创建聊天区域
    const chatArea = document.createElement('div');
    chatArea.className = 'chat-area';
    chatArea.dataset.chatId = userName;
    chatArea.innerHTML = `
        <div class="chat-header">
            <div class="header-info">
                <h2>👤 ${escapeHtml(userName)}</h2>
                <div class="header-subtitle">与 ${escapeHtml(userName)} 的私聊</div>
            </div>
        </div>
        
        <div class="messages-container" id="messages-${userName}">
            <div class="welcome-message">
                <div class="welcome-icon">💬</div>
                <div class="welcome-title">与 ${escapeHtml(userName)} 的私聊</div>
                <div class="welcome-subtitle">开始对话吧！</div>
            </div>
        </div>
        
        <div class="chat-input">
            <div class="input-container">
                <div class="input-main-row">
                    <input class="message-input" placeholder="发送私聊消息给 ${escapeHtml(userName)}... (按 Enter 发送)" autocomplete="off">
                    <button class="send-btn">
                        <span class="btn-icon">📤</span>
                        <span class="btn-text">发送</span>
                    </button>
                </div>
            </div>
        </div>
    `;
    
    contentContainer.appendChild(chatArea);
    
    // 绑定输入事件
    const input = chatArea.querySelector('.message-input');
    const sendBtn = chatArea.querySelector('.send-btn');
    sendBtn.addEventListener('click', () => sendMessage(input, userName));
    input.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') sendMessage(input, userName);
    });
    
    // 保存到映射
    privateChatTabs.set(userName, { tab, chatArea });
    
    console.log(`Created private chat tab for: ${userName}`);
}

function switchToChat(chatId) {
    // 移除所有标签的 active 类
    document.querySelectorAll('.chat-tab').forEach(tab => tab.classList.remove('active'));
    document.querySelectorAll('.chat-area').forEach(area => area.classList.remove('active'));
    
    // 激活目标标签
    const targetTab = document.querySelector(`[data-chat-id="${chatId}"]`);
    const targetArea = document.querySelector(`.chat-area[data-chat-id="${chatId}"]`);
    
    if (targetTab && targetArea) {
        targetTab.classList.add('active');
        targetArea.classList.add('active');
        activeChat = chatId;
        
        // 清除未读计数
        clearUnreadCount(chatId);
        
        // 标记当前聊天的所有消息为已读
        markChatAsRead(chatId);
        
        // 滚动到底部
        const messagesContainer = targetArea.querySelector('.messages-container');
        if (messagesContainer) {
            scrollToBottomOf(messagesContainer);
        }
        
        console.log(`Switched to chat: ${chatId}`);
    }
}

function closePrivateChatTab(userName) {
    const info = privateChatTabs.get(userName);
    if (!info) return;
    
    // 移除元素
    info.tab.remove();
    info.chatArea.remove();
    privateChatTabs.delete(userName);
    unreadCounts.delete(userName);
    
    // 如果关闭的是当前激活的标签，切换到群聊
    if (activeChat === userName) {
        switchToChat('group');
    }
    
    console.log(`Closed private chat tab: ${userName}`);
}

// ========== 未读消息管理 ==========

function increaseUnreadCount(chatId) {
    const currentCount = unreadCounts.get(chatId) || 0;
    const newCount = currentCount + 1;
    unreadCounts.set(chatId, newCount);
    
    const tab = document.querySelector(`[data-chat-id="${chatId}"]`);
    if (tab) {
        const badge = tab.querySelector('.unread-badge');
        if (badge) {
            badge.textContent = newCount;
            badge.style.display = 'inline-block';
        }
    }
}

function clearUnreadCount(chatId) {
    unreadCounts.set(chatId, 0);
    
    const tab = document.querySelector(`[data-chat-id="${chatId}"]`);
    if (tab) {
        const badge = tab.querySelector('.unread-badge');
        if (badge) {
            badge.style.display = 'none';
        }
    }
    
    // 保存到 localStorage
    saveUnreadCountsToStorage();
}

// ========== 消息创建函数 ==========

function createSystemMessage(content) {
    const div = document.createElement('div');
    div.className = 'message system';
    div.innerHTML = `
        <div class="message-bubble">${escapeHtml(content)}</div>
    `;
    return div;
}

function createChatMessage(obj, msgContent, isOwn) {
    const div = document.createElement('div');
    div.className = `message ${isOwn ? 'own' : 'other'}`;
    
    const avatar = getAvatar(obj.fromName);
    const time = formatTime(obj.ts);
    
    div.innerHTML = `
        <div class="message-avatar">${avatar}</div>
        <div class="message-content">
            <div class="message-sender">${escapeHtml(obj.fromName || 'unknown')}</div>
            <div class="message-bubble">${escapeHtml(msgContent)}</div>
            <div class="message-time">${time}</div>
        </div>
    `;
    return div;
}

function removeWelcomeMessage(container) {
    const welcomeMsg = container.querySelector('.welcome-message');
    if (welcomeMsg) {
        welcomeMsg.remove();
    }
}

function scrollToBottomOf(container) {
    if (container) {
        container.scrollTop = container.scrollHeight;
    }
}

function getAvatar(name) {
    return name ? name.charAt(0).toUpperCase() : '?';
}

function formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function updateConnectionStatus(connected) {
    const indicator = document.getElementById('statusIndicator');
    const statusText = document.getElementById('statusText');
    if (connected) {
        indicator.classList.remove('disconnected');
        statusText.textContent = '已连接';
    } else {
        indicator.classList.add('disconnected');
        statusText.textContent = '连接断开';
    }
}

function updateOnlineUsersList() {
    const container = document.getElementById('onlineUsers');
    const onlineCount = document.getElementById('onlineCount');
    
    // 更新计数（排除自己）
    const othersCount = onlineUsers.size - 1;
    onlineCount.textContent = othersCount;
    
    if (onlineUsers.size <= 1) {
        container.innerHTML = '<div class="empty-state">暂无其他用户</div>';
        return;
    }
    
    container.innerHTML = '';
    onlineUsers.forEach(user => {
        if (user !== username) { // 不显示自己
            const div = document.createElement('div');
            div.className = 'user-item';
            
            const isFriend = friendsList.has(user);
            
            div.innerHTML = `
                <div class="user-item-avatar">${getAvatar(user)}</div>
                <div class="user-item-name" style="cursor: pointer;" onclick="openPrivateChat('${escapeHtml(user)}')">${escapeHtml(user)}</div>
                <div class="user-item-actions">
                    ${isFriend 
                        ? `<button class="btn-remove-friend" onclick="event.stopPropagation(); removeFriend('${escapeHtml(user)}')">删除</button>`
                        : `<button class="btn-add-friend" onclick="event.stopPropagation(); addFriend('${escapeHtml(user)}')">添加</button>`
                    }
                </div>
            `;
            container.appendChild(div);
        }
    });
}

// 打开私聊窗口
function openPrivateChat(user) {
    if (!privateChatTabs.has(user)) {
        createPrivateChatTab(user);
    }
    switchToChat(user);
}

function addSystemNotification(message) {
    const container = document.getElementById('systemNotifications');
    const div = document.createElement('div');
    div.className = 'notification-item';
    div.textContent = message;
    container.insertBefore(div, container.firstChild);
    
    // 最多保留 5 条通知
    while (container.children.length > 5) {
        container.removeChild(container.lastChild);
    }
}

document.getElementById('btnSwitch').addEventListener('click', async () => {
    const newRoom = prompt('输入要切换的房间ID', roomId);
    if (!newRoom || newRoom === roomId) return;
    
    try {
        await fetch('/auth/switchRoom', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `roomId=${encodeURIComponent(newRoom)}`
        });
        roomId = newRoom;
        document.getElementById('curRoom').textContent = roomId;
        document.getElementById('chatRoomName').textContent = roomId;
        
        // 清空群聊消息
        const groupMessages = document.getElementById('messages-group');
        if (groupMessages) {
            groupMessages.innerHTML = '';
        }
        lastSeq = 0;
        
        // 关闭所有私聊标签
        const privateUsers = Array.from(privateChatTabs.keys());
        privateUsers.forEach(user => closePrivateChatTab(user));
        
        // 切换回群聊标签
        switchToChat('group');
        
        // 重置在线用户列表
        onlineUsers.clear();
        onlineUsers.add(username);
        updateOnlineUsersList();
        
        // ✅ 清空消息去重缓存
        receivedMessageIds.clear();
        
        // 清空系统通知
        document.getElementById('systemNotifications').innerHTML = '<div class="notification-item">已切换到新房间</div>';
        
        // 断开并重连到新房间
        ws.close();
    } catch (e) {
        console.error('Failed to switch room:', e);
        alert('切换房间失败，请重试');
    }
});

// 退出登录
document.getElementById('btnLogout').addEventListener('click', async () => {
    if (!confirm('确定要退出登录吗？')) {
        return;
    }
    
    try {
        // 关闭 WebSocket 连接
        if (ws) {
            ws.close();
        }
        
        // 调用登出接口
        await fetch('/auth/logout', {
            method: 'POST'
        });
        
        // 跳转到登录页面
        window.location.href = 'login.html';
    } catch (e) {
        console.error('Failed to logout:', e);
        // 即使登出失败也跳转到登录页面
        window.location.href = 'login.html';
    }
});

// ==================== 好友功能 ====================

let friendsList = new Set(); // 好友列表

// 加载好友列表
async function loadFriendsList() {
    try {
        const response = await fetch('/friends/list');
        const data = await response.json();
        
        if (data.code === 200 && data.data) {
            friendsList.clear();
            data.data.forEach(friend => friendsList.add(friend.username));
            updateFriendsListUI();
        }
    } catch (error) {
        console.error('加载好友列表失败:', error);
    }
}

// 更新好友列表UI
function updateFriendsListUI() {
    const container = document.getElementById('friendsList');
    const countBadge = document.getElementById('friendCount');
    
    container.innerHTML = '';
    countBadge.textContent = friendsList.size;
    
    if (friendsList.size === 0) {
        container.innerHTML = '<div class="empty-state">暂无好友</div>';
        return;
    }
    
    friendsList.forEach(friendUsername => {
        const div = document.createElement('div');
        div.className = 'friend-item';
        div.innerHTML = `
            <div class="friend-item-avatar">${getAvatar(friendUsername)}</div>
            <div class="friend-item-name" onclick="openPrivateChat('${escapeHtml(friendUsername)}')">${escapeHtml(friendUsername)}</div>
            <div class="user-item-actions">
                <button class="btn-remove-friend" onclick="removeFriend('${escapeHtml(friendUsername)}')">删除</button>
            </div>
        `;
        container.appendChild(div);
    });
}

// 添加好友
async function addFriend(friendUsername) {
    if (friendUsername === username) {
        alert('不能添加自己为好友');
        return;
    }
    
    if (friendsList.has(friendUsername)) {
        alert('已经是好友了');
        return;
    }
    
    try {
        const formData = new URLSearchParams();
        formData.append('friendUsername', friendUsername);
        
        const response = await fetch('/friends/add', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: formData
        });
        
        const data = await response.json();
        
        if (data.code === 200) {
            friendsList.add(friendUsername);
            updateFriendsListUI();
            updateOnlineUsersList(); // 刷新在线用户列表显示
            addSystemNotification(`已添加 ${friendUsername} 为好友`);
        } else {
            alert(data.message || '添加好友失败');
        }
    } catch (error) {
        console.error('添加好友失败:', error);
        alert('添加好友失败，请重试');
    }
}

// 删除好友
async function removeFriend(friendUsername) {
    if (!confirm(`确定要删除好友 ${friendUsername} 吗？`)) {
        return;
    }
    
    try {
        const formData = new URLSearchParams();
        formData.append('friendUsername', friendUsername);
        
        const response = await fetch('/friends/remove', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: formData
        });
        
        const data = await response.json();
        
        if (data.code === 200) {
            friendsList.delete(friendUsername);
            updateFriendsListUI();
            updateOnlineUsersList(); // 刷新在线用户列表显示
            addSystemNotification(`已删除好友 ${friendUsername}`);
        } else {
            alert(data.message || '删除好友失败');
        }
    } catch (error) {
        console.error('删除好友失败:', error);
        alert('删除好友失败，请重试');
    }
}

// ==================== 已读消息和未读计数持久化 ====================

// 保存未读计数到 localStorage
function saveUnreadCountsToStorage() {
    try {
        const data = {};
        unreadCounts.forEach((count, chatId) => {
            if (count > 0) {
                data[chatId] = count;
            }
        });
        localStorage.setItem(getStorageKey('unreadCounts'), JSON.stringify(data));
    } catch (error) {
        console.error('保存未读计数失败:', error);
    }
}

// 从 localStorage 加载未读计数
function loadUnreadCountsFromStorage() {
    try {
        const stored = localStorage.getItem(getStorageKey('unreadCounts'));
        if (stored) {
            const data = JSON.parse(stored);
            Object.keys(data).forEach(chatId => {
                const count = data[chatId];
                if (count > 0) {
                    unreadCounts.set(chatId, count);
                    // 更新UI
                    const tab = document.querySelector(`[data-chat-id="${chatId}"]`);
                    if (tab) {
                        const badge = tab.querySelector('.unread-badge');
                        if (badge) {
                            badge.textContent = count;
                            badge.style.display = 'inline-block';
                        }
                    }
                }
            });
            console.log('已加载未读计数');
        }
    } catch (error) {
        console.error('加载未读计数失败:', error);
    }
}

// 获取存储键名
function getStorageKey(key) {
    return `chat_${username}_${key}`;
}

// 标记聊天为已读
function markChatAsRead(chatId) {
    if (!readMessages.has(chatId)) {
        readMessages.set(chatId, new Set());
    }
    
    // 获取该聊天的所有消息元素
    const messagesContainer = document.getElementById(chatId === 'group' ? 'messages-group' : `messages-${chatId}`);
    if (messagesContainer) {
        const messages = messagesContainer.querySelectorAll('.message:not(.system)');
        messages.forEach(msg => {
            // 使用消息的时间戳和发送者作为唯一标识
            const sender = msg.querySelector('.message-sender')?.textContent || '';
            const time = msg.querySelector('.message-time')?.textContent || '';
            const messageId = `${sender}_${time}`;
            readMessages.get(chatId).add(messageId);
        });
    }
    
    saveReadMessagesToStorage();
}

// 保存已读消息到 localStorage
function saveReadMessagesToStorage() {
    try {
        const data = {};
        readMessages.forEach((messageSet, chatId) => {
            data[chatId] = Array.from(messageSet);
        });
        localStorage.setItem(getStorageKey('readMessages'), JSON.stringify(data));
    } catch (error) {
        console.error('保存已读消息失败:', error);
    }
}

// 从 localStorage 加载已读消息
function loadReadMessagesFromStorage() {
    try {
        const stored = localStorage.getItem(getStorageKey('readMessages'));
        if (stored) {
            const data = JSON.parse(stored);
            readMessages.clear();
            Object.keys(data).forEach(chatId => {
                readMessages.set(chatId, new Set(data[chatId]));
            });
            console.log('已加载已读消息记录');
        }
    } catch (error) {
        console.error('加载已读消息失败:', error);
    }
}

// 清除当前用户的所有存储数据
function clearUserStorage() {
    try {
        localStorage.removeItem(getStorageKey('readMessages'));
        localStorage.removeItem(getStorageKey('unreadCounts'));
        console.log('已清除用户存储数据');
    } catch (error) {
        console.error('清除存储数据失败:', error);
    }
}
